package com.pys.beans;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.apache.commons.lang.StringUtils;

import com.pys.common.beans.BaseBean;
import com.pys.pojo.PysRole;
import com.pys.service.RoleService;
import com.pys.utils.FacesUtils;

@ManagedBean
@ViewScoped
public class RoleBean extends BaseBean implements Serializable {
	private String ad;
	private boolean durum = true;
	private List<PysRole> list;
	private PysRole selectedRole;

	public RoleBean() {
		refreshList();
	}

	/*
	 * ACTIONS
	 */
	public void refreshList() {
		RoleService roleService = new RoleService();
		list = roleService.getAllList(false);
	}

	public void saveAction() {
		if (StringUtils.isBlank(ad)) {
			FacesUtils.addMessage(FacesMessage.SEVERITY_ERROR,
					"VALIDATION_ROLE_AD");
			return;
		}

		RoleService roleService = new RoleService();
		if (selectedRole == null) {
			PysRole pysRole = new PysRole();
			pysRole.setAd(ad);
			pysRole.setDurum(durum);
			pysRole.setKullaniciId(FacesUtils.getUserSession().getCurrentUser()
					.getId());
			pysRole.setOlusturmaTarih(new Date());
			roleService.save(pysRole);
		} else {
			selectedRole.setAd(ad);
			selectedRole.setDurum(durum);
			selectedRole.setKullaniciId(FacesUtils.getUserSession()
					.getCurrentUser().getId());
			selectedRole.setGuncellemeTarih(new Date());
			roleService.update(selectedRole);
		}
		refreshList();
		clear();
		FacesUtils.successMessage();
	}

	public void deleteAction() {
		RoleService roleService = new RoleService();
		selectedRole.setDeleted(true);
		roleService.update(selectedRole);
		refreshList();
		clear();
		FacesUtils.successMessage();
	}

	public void updateAction() {
		ad = selectedRole.getAd();
		durum = selectedRole.isDurum();
	}

	public void clear() {
		selectedRole = null;
		ad = null;
		durum = true;
	}

	/*
	 * GETTER_SETTER
	 */

	public String getAd() {
		return ad;
	}

	public void setAd(String ad) {
		this.ad = ad;
	}

	public List<PysRole> getList() {
		return list;
	}

	public void setList(List<PysRole> list) {
		this.list = list;
	}

	public PysRole getSelectedRole() {
		return selectedRole;
	}

	public void setSelectedRole(PysRole selectedRole) {
		this.selectedRole = selectedRole;
	}

	public boolean isDurum() {
		return durum;
	}

	public void setDurum(boolean durum) {
		this.durum = durum;
	}

}
